/*
 * @Description: 自增字段上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-10-31 17:39:34
 */

import React, { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { AutoIncreaseReducer } from '../reducers/AutoIncreaseReducer';
import { SET_COMMON_RULES, SET_SELECT_AT, SET_SELECT_FOND, SET_SELECT_LEVEL } from '../constants';
import { isNullObj } from '@/utils';
import {
  addGroupSortRule,
  editGroupSortRule,
  fetchGroupSortRule
} from '@/api/rulesettings/groupSortRule';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectLevel: {},

  // 分组排列规则
  commonRule: {}
};

const AutoIncreaseContext = createContext();

const AutoIncreaseContextProvider = (props) => {
  const [state, dispatch] = useReducer(AutoIncreaseReducer, initialState);

  const actions = {
    /**
     * @description: 打开新增全宗弹窗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setCommonRules(data) {
      dispatch({ type: SET_COMMON_RULES, data });
    },

    /**
     * @description: 获取分组字段列表
     */
    getSelectFields() {
      const query = {
        atCode: state.selectAT.atCode,
        atType: state.selectAT.atType,
        level: state.selectLevel.level
      };
      fetchGroupSortRule(query).then((res) => {
        const data = res.data || {};

        dispatch({ type: SET_COMMON_RULES, data });
      });
    },

    saveGroupSortRuleFunc(query) {
      const { selectAT, selectLevel } = state;

      if (query.id) {
        editGroupSortRule(query).then((res) => {
          message.success('保存成功');
          const { data } = res;
          dispatch({ type: SET_COMMON_RULES, data });
        });
      } else {
        const coordinate = {
          atType: selectAT.atType,
          atCode: selectAT.atCode,
          level: selectLevel.level
        };
        addGroupSortRule({ ...query, ...coordinate }).then((res) => {
          message.success('保存成功');
          const { data } = res;
          dispatch({ type: SET_COMMON_RULES, data });
        });
      }
    }
  };

  // watch选中的单位来加载自增字段
  useEffect(() => {
    if (!isNullObj(state.selectLevel)) {
      actions.getSelectFields();
    }
  }, [state.selectLevel]);

  return (
    <AutoIncreaseContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </AutoIncreaseContext.Provider>
  );
};

export const useAutoIncreaseContext = () => {
  return useContext(AutoIncreaseContext);
};

export { AutoIncreaseContext, AutoIncreaseContextProvider };
